<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
        <title>《Flutter—State生命周期》 - 飞雪无情的博客</title><meta name="Description" content="专注于IT互联网，包括但不限于Go语言(golang)、Java、Android、Python、项目管理、抖音分析、软件架构等"><meta property="og:title" content="《Flutter—State生命周期》" />
<meta property="og:description" content="
本文主要介绍类比 Android 和 iOS，了解 Flutter State 的生命周期。
" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://www.flysnow.org/posts/flutter/flutterState%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F/" />
<meta property="article:published_time" content="2021-07-31T18:19:45+08:00" />
<meta property="article:modified_time" content="2021-07-31T18:19:45+08:00" />
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="《Flutter—State生命周期》"/>
<meta name="twitter:description" content="
本文主要介绍类比 Android 和 iOS，了解 Flutter State 的生命周期。
"/>
<meta name="application-name" content="飞雪无情的博客">
<meta name="apple-mobile-web-app-title" content="飞雪无情的博客"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
        <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
        <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://www.flysnow.org/posts/flutter/flutterState%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F/" /><link rel="prev" href="https://www.flysnow.org/posts/flutter/Flutter/" /><link rel="next" href="https://www.flysnow.org/posts/flutter/flutterOverlay%E7%94%A8%E6%B3%95/" /><link rel="stylesheet" href="/lib/normalize/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "《Flutter—State生命周期》",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/www.flysnow.org\/posts\/flutter\/flutterState%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F\/"
        },"genre": "posts","keywords": "flutter","wordcount":  1410 ,
        "url": "https:\/\/www.flysnow.org\/posts\/flutter\/flutterState%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F\/","datePublished": "2021-07-31T18:19:45+08:00","dateModified": "2021-07-31T18:19:45+08:00","publisher": {
            "@type": "Organization",
            "name": "飞雪无情"},"author": {
                "@type": "Person",
                "name": "飞雪无情"
            },"description": ""
    }
    </script></head>
    <body header-desktop="" header-mobile=""><script type="text/javascript">(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : '' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><div class="logo-wrapper">
  <a href="/%20/" class="logo">飞雪无情的博客</a>
</div>

<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
      <a class="menu-item-link" href="/tools/">工具</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/archives/">归档</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/about/">关于</a>
    </li>
  </ul>
</nav><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">Contents</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single"><h1 class="single-title animated flipInX">《Flutter—State生命周期》</h1><div class="post-meta">
            <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>飞雪无情</a></span>&nbsp;<span class="post-category">included in <a href="/categories/Flutter/"><i class="far fa-folder fa-fw"></i>Flutter</a></span></div>
            <div class="post-meta-line"><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2021-07-31">2021-07-31</time>&nbsp;<i class="fas fa-pencil-alt fa-fw"></i>&nbsp;1410 words&nbsp;
                <i class="far fa-clock fa-fw"></i>&nbsp;3 minutes&nbsp;</div>
        </div><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        data-srcset="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 1.5x, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 2x"
        data-sizes="auto"
        alt="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        title="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png" /></div><div class="details toc" id="toc-static"  kept="">
                <div class="details-summary toc-title">
                    <span>Contents</span>
                    <span><i class="details-icon fas fa-angle-right"></i></span>
                </div>
                <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#statefulwidget">StatefulWidget</a>
      <ul>
        <li><a href="#createstate">createState():</a></li>
        <li><a href="#initstate">initState()</a></li>
        <li><a href="#mounted">mounted</a></li>
        <li><a href="#addpostframecallback">addPostFrameCallback</a></li>
        <li><a href="#didchangedependencies">didChangeDependencies</a></li>
        <li><a href="#build">build()</a></li>
        <li><a href="#didupdatewidget">didUpdateWidget()</a></li>
        <li><a href="#deactivate">deactivate()</a></li>
        <li><a href="#dispose">dispose()</a></li>
      </ul>
    </li>
  </ul>
</nav></div>
            </div><div class="content" id="content"><blockquote>
<p>本文主要介绍类比 Android 和 iOS，了解 Flutter State 的生命周期。</p>
</blockquote>
<p>从 Android 或 iOS 转到 Flutter 开发，最让人疑惑的是 Flutter 如何处理生命周期。</p>
<p><strong>onCreate()</strong> 在哪里？<strong>viewDidLoad()</strong> 呢？我应该将业务逻辑放在哪里？为什么只有一个 <code>build</code> 方法？</p>
<p>本文将解答这些疑惑。</p>
<h1 id="android">Android</h1>
<p><strong>Activity</strong> 生命周期是 Android 开发必须记住的：</p>
<ul>
<li>onCreate</li>
<li>onStart</li>
<li>onResume</li>
</ul>
<hr>
<ul>
<li>onPause</li>
<li>onStop</li>
<li>onRestart</li>
<li>onDestroy</li>
</ul>
<p>大部分业务逻辑放在 <strong>onCreate</strong> 方法：初始化 view、数据库、监听器等等。<strong>onResume</strong> 和 <strong>onPause</strong> 是判断用户离开或进入当前页面的好时机。</p>
<h1 id="ios">iOS</h1>
<p>UIViewController 的生命周期如下：</p>
<ul>
<li>viewDidLoad</li>
<li>viewWillAppear</li>
<li>viewDidAppear</li>
</ul>
<hr>
<ul>
<li>viewWillDisappear</li>
<li>viewDidDisappear</li>
<li>viewDidUnload</li>
</ul>
<p>如你所见，两个平台均使用几乎一致的步骤来创建或销毁页面。大部分业务逻辑放在 <strong>viewDidLoad()</strong>，而 <strong>Will/Did Appear/Disappear</strong> 用于保存信息，判断用户何时离开页面等等。</p>
<h1 id="flutter">Flutter</h1>
<p>在 Flutter 中呢？Widget 也遵循类似规则吗？</p>
<p>Flutter 中主要有两种 Widget：<strong>StatelessWidget</strong> 和 <strong>StatefulWidget</strong>。本文重点放在 <strong>StatefulWidget</strong>，因为它有点像 <strong>Android</strong> 和 <strong>iOS</strong> 中的某些概念。</p>
<h2 id="statefulwidget">StatefulWidget</h2>
<p>StatefulWidget 是最重要的 Widget，因为它持有 <strong>State</strong>，它知道何时发生变化并进行必要的重绘。它的生命周期如下：</p>
<ul>
<li>createState</li>
<li>initState</li>
<li>didChangeDependencies</li>
<li>build</li>
<li>(didUpdateWidget)</li>
</ul>
<p>— — — — — — — — — — —</p>
<ul>
<li>deactivate</li>
<li>dispose</li>
</ul>
<p>你可能会注意到创建阶段的 state 比销毁阶段的多，这是因为创建/重建 Widget 及其 State 更复杂。</p>
<h3 id="createstate">createState():</h3>
<p>构建新的 StatefulWidget 时将调用 createState()，StatefulWidget 的子类必须覆盖这个方法：</p>
<pre><code>class MyScreen extends StatefulWidget {
  @override
  _MyScreenState createState() =&gt; _MyScreenState();
}
</code></pre><h3 id="initstate">initState()</h3>
<p>通常需要重写这个方法。它是 Widget 创建后调用的第一个方法，可以理解成 <strong>onCreate()</strong> 或 <strong>viewDidLoad()</strong> 的等价物。在这个方法中可以检查 Widget 某些相关属性：是否有被渲染？当前是否处理 mounted 状态？</p>
<h3 id="mounted">mounted</h3>
<p>每个 Widget 都有这个属性。当为 Widget.buildContext 赋值后 mounted 的值变成 <strong>true</strong>，Widget 在树中。直到 <strong>dispose</strong> 方法被调用前，mounted 一直为 true。</p>
<h3 id="addpostframecallback">addPostFrameCallback</h3>
<p>可以在 <strong>initState</strong> 方法中按如下方式调用 <code>addPostFrameCallback</code>：</p>
<pre><code>import 'package:flutter/scheduler.dart';
@override
void initState() {
  super.initState();
  SchedulerBinding.instance.addPostFrameCallback((_) =&gt; {});
}
</code></pre><p>这个方法为一帧结束时添加回调，回调方法只会调用一次，通知 Widget 构建已完成。</p>
<h3 id="didchangedependencies">didChangeDependencies</h3>
<p>widget 构建时第一次调用 initState() 后立即会调用 didChangeDependencies()。如果 <strong>StatefulWidgets</strong> 依赖某个 <strong>InheritedWidget</strong>，后者发生变化时会导致 didChangeDependencies() 再次被调用。</p>
<h3 id="build">build()</h3>
<p>可以肯定地说这是最重要的方法。这个方法依赖整个待渲染的 Widget 树，在 <strong>didChangeDependencies()</strong> 立即被调用。所有的 GUI 渲染发生在这个方法，每次 UI 需要重新渲染时都会调用这个方法。(重新渲染是很廉价的操作)</p>
<h3 id="didupdatewidget">didUpdateWidget()</h3>
<p>这是一个不太常见的生命周期方法。一旦 parent widget 有变化需要重绘 UI 时会调用 didUpdateWidget()。这个方法有一个 <strong>oldWidget</strong> 参数，可以将它跟当前 <strong>widget</strong> 进行比较以执行某些额外的业务逻辑。</p>
<h3 id="deactivate">deactivate()</h3>
<p>这个生命周期方法也不太常见。这个方法被调用时，意味着 Widget 开始进入”死亡”阶段。</p>
<p>当 framework 从树中移除 State 时会调用本方法。某些情况下，framework 会重新将 State 对象加入到树中。</p>
<h3 id="dispose">dispose()</h3>
<p>这个方法也非常重要。当 Widget 及其 State 从树中永久移除时会调用这个方法。此后 Widget 不会再被构建。</p>
<p>你需要在这个方法中做取消对 stream 的监听、销毁动画等操作。它是 <strong>initState</strong> 的反操作。</p>
<h1 id="widgetsbindingobserver">WidgetsBindingObserver</h1>
<p>如果我们想监听应用何时进入后台该怎么办？</p>
<p>可以这样做。对 <strong>StatefulWidget</strong> 做些小改动：</p>
<pre><code>class _MyScreenState extends State&lt;MyScreen&gt; with WidgetsBindingObserver
</code></pre><p>我们让 <code>_MyScreenState</code> 实现了抽象类 <strong>WidgetsBindingObserver</strong>，之后就可以观察应用的生命周期状态。在 <strong>initState</strong> 方法中开始观察：</p>
<pre><code>WidgetsBinding.instance.addObserver(this);
</code></pre><p>在 <strong>dispose</strong> 方法中停止观察：</p>
<pre><code>WidgetsBinding.instance.removeObserver(this);
</code></pre><p>接下来在 <strong>didChangeAppLifecycleState</strong> 接收生命周期的变化即可：</p>
<pre><code>@override
void didChangeAppLifecycleState(AppLifecycleState state) {
  super.didChangeAppLifecycleState(state);
  if (state == AppLifecycleState.paused) {
    // went to Background
  }
  if (state == AppLifecycleState.resumed) {
    // came back to Foreground
  }
}
</code></pre><p>这个技巧很有用。如果你想在应用进入后台时弹出 notification，或者保存数据，又或者在用户点 back 回退时弹出 popup，都可以使用这个技巧。</p></div><div class="post-footer" id="post-footer">
    <div class="post-info">
        <div class="post-info-line">
            <div class="post-info-mod">
                <span>Updated on 2021-07-31</span>
            </div>
            <div class="post-info-license"></div>
        </div>
        <div class="post-info-line">
            <div class="post-info-md"></div>
            <div class="post-info-share">
                <span></span>
            </div>
        </div>
    </div>

    <div class="post-info-more">
        <section class="post-tags"><i class="fas fa-tags fa-fw"></i>&nbsp;<a href="/tags/flutter/">flutter</a></section>
        <section>
            <span><a href="javascript:void(0);" onclick="window.history.back();">Back</a></span>&nbsp;|&nbsp;<span><a href="/">Home</a></span>
        </section>
    </div>

    <div class="post-nav"><a href="/posts/flutter/Flutter/" class="prev" rel="prev" title="《Flutter中的底部导航栏切换》"><i class="fas fa-angle-left fa-fw"></i>《Flutter中的底部导航栏切换》</a>
            <a href="/posts/flutter/flutterOverlay%E7%94%A8%E6%B3%95/" class="next" rel="next" title="《Flutter—Overlay用法》">《Flutter—Overlay用法》<i class="fas fa-angle-right fa-fw"></i></a></div>
</div>
</article></div>
            </main><footer class="footer">
        <div class="footer-container"><div class="footer-line">Powered by <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.79.1">Hugo</a> | Theme - <a href="https://github.com/dillonzq/LoveIt" target="_blank" rel="noopener noreffer" title="LoveIt 0.2.10"><i class="far fa-kiss-wink-heart fa-fw"></i> LoveIt</a>
                </div><div class="footer-line"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2021</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/" target="_blank">飞雪无情</a></span></div>
        </div>
    </footer></div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="Back to Top">
                <i class="fas fa-arrow-up fa-fw"></i>
            </a><a href="#" id="view-comments" class="fixed-button" title="View Comments">
                <i class="fas fa-comment fa-fw"></i>
            </a>
        </div><script type="text/javascript" src="/lib/smooth-scroll/smooth-scroll.min.js"></script><script type="text/javascript" src="/lib/lazysizes/lazysizes.min.js"></script><script type="text/javascript" src="/lib/clipboard/clipboard.min.js"></script><script type="text/javascript" src="/lib/sharer/sharer.min.js"></script><script type="text/javascript">window.config={"code":{"copyTitle":"Copy to clipboard","maxShownLines":10},"comment":{}};</script><script type="text/javascript" src="/js/theme.min.js"></script></body>
</html>
